<template>
	<!-- @touchstart="closePop" -->
	<uni-popup ref="popupRef" type="bottom" @change="handlePopupChange" :safe-area="false">
		<view v-if="isShow" class="input_pop" :style="{ bottom: inputBottom + 'px', paddingBottom: paddingHeight + 'px' }">
			<view class="input">
				<textarea
					ref="textareaRef"
					:show-confirm-bar="false"
					:adjust-position="false"
					:focus="isFocus"
					:auto-height="true"
					:disable-default-padding="true"
					:hold-keyboard="true"
					:cursor-spacing="20"
					placeholder="与人善言，暖于布帛"
					class="input-inner"
					v-model="params.content"
					@focus="inputFocus"
					@blur="inputBlur"
					@confirm="confirmInput"
					@keyboardheightchange="onKeyboardHeightChange"
				/>
				<view class="imglist">
					<view class="items" v-for="(item, index) in params.images" :key="index">
						<image :src="item" mode="aspectFill"></image>
						<image src="/static/close.png" mode="" class="icon" @click="removeIMG(index)"></image>
					</view>
					<view class="items1 flex_jc_cent" @tap="chooseFENGMIAN">
						<uni-icons type="plusempty" color="#979797"></uni-icons>
					</view>
				</view>
			</view>
			<view class="button_f flex_jc_sb">
				<view class="" @tap="chooseFENGMIAN">
					<image src="/static/xc.png" mode=""></image>
				</view>
				<view class="btn" :class="btnactive ? 'btn_active' : ''" @click="submitComment">发表</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
import { ref, nextTick, watch, onMounted, onUnmounted, getCurrentInstance, reactive, computed } from 'vue';
import { articleReply } from '@/api/community.js';
import { chooseAndUploadImage } from '@/utils/upload';
import { toast, showConfirm } from '@/utils/common.js';

const popupRef = ref(null);
const textareaRef = ref(null);
const inputBottom = ref(0);
const keyboardHeight = ref(0);
const isAndroid = ref(false);
const isIOS = ref(false);
const isShow = ref(false);
const isFocus = ref(false);
const paddingHeight = ref(0);
const keepFocusTimer = ref(null);
const isSubmitting = ref(false);

// 新增：安卓专用状态
const androidFocusLock = ref(false); // 安卓聚焦锁，防止重复聚焦
const androidBlurCount = ref(0); // 安卓失去焦点计数

// 页面状态管理
const pageVisible = ref(true);
const wasOpenedBeforeHide = ref(false);
const instance = getCurrentInstance();

const closePop = () => {
    // 关闭时清理
    popupRef.value.close();
    setTimeout(() => {
        isFocus.value = false;
        isSubmitting.value = false;
        inputBottom.value = 0;
        keyboardHeight.value = 0;
        isShow.value = false;
        clearTimeout(keepFocusTimer.value);
        wasOpenedBeforeHide.value = false;
        androidFocusLock.value = false;
        androidBlurCount.value = 0;
        // 重置内容
        params.content = '';
        params.images = [];
    }, 100);
};

// 初始化平台检测
onMounted(() => {
    const systemInfo = uni.getSystemInfoSync();
    isAndroid.value = systemInfo.platform === 'android';
    isIOS.value = systemInfo.platform === 'ios';
    console.log('当前平台:', isAndroid.value ? 'Android' : 'iOS');

    // 监听页面显示/隐藏
    setupPageListeners();
});

const setupPageListeners = () => {
    // 页面显示事件
    uni.$on('pageShow', () => {
        pageVisible.value = true;
        handlePageShow();
    });

    // 页面隐藏事件
    uni.$on('pageHide', () => {
        pageVisible.value = false;
        handlePageHide();
    });
};

const handlePageShow = () => {
    if (wasOpenedBeforeHide.value && !isShow.value) {
        setTimeout(() => {
            open();
            wasOpenedBeforeHide.value = false;
        }, 100);
    }
};

const handlePageHide = () => {
    if (isShow.value) {
        wasOpenedBeforeHide.value = true;
    }
    isFocus.value = false;
    clearTimeout(keepFocusTimer.value);
    androidFocusLock.value = false;
};

const btnactive = computed(() => {
    return params.content.trim().length > 0;
});

// 键盘高度变化 - 安卓专用处理
const onKeyboardHeightChange = (e) => {
    if (!pageVisible.value) return;

    const systemInfo = uni.getSystemInfoSync();
    paddingHeight.value = isAndroid.value ? 30 : systemInfo.safeAreaInsets.bottom || 10;

    if (e.detail.height > 0) {
        keyboardHeight.value = e.detail.height;
        inputBottom.value = e.detail.height - paddingHeight.value;
        
        // 安卓：键盘弹出时延迟聚焦
        if (isAndroid.value) {
            setTimeout(() => {
                if (isShow.value && pageVisible.value) {
                    safeForceFocus();
                }
            }, 200);
        } else {
            // iOS正常处理
            setTimeout(() => {
                if (isShow.value && pageVisible.value) {
                    forceFocus();
                }
            }, 50);
        }
    } else {
        // 键盘收起
        inputBottom.value = 0;
        keyboardHeight.value = 0;
        // 安卓：键盘收起时重置状态
        if (isAndroid.value) {
            androidFocusLock.value = false;
            androidBlurCount.value = 0;
        }
    }
};

// 安卓安全的强制聚焦方法
const safeForceFocus = () => {
    if (!isShow.value || !pageVisible.value || androidFocusLock.value) return;
    
    androidFocusLock.value = true;
    isFocus.value = false;
    
    nextTick(() => {
        setTimeout(() => {
            isFocus.value = true;
            androidFocusLock.value = false;
            
            // 确保textarea组件接收到焦点
            setTimeout(() => {
                if (textareaRef.value && textareaRef.value.$el) {
                    textareaRef.value.$el.focus();
                }
            }, 50);
        }, 100);
    });
};

// iOS的正常强制聚焦方法
const forceFocus = () => {
    if (!isShow.value || !pageVisible.value) return;

    isFocus.value = false;
    nextTick(() => {
        isFocus.value = true;
        setTimeout(() => {
            if (textareaRef.value && textareaRef.value.$el) {
                textareaRef.value.$el.focus();
            }
        }, 80);
    });
};

// 弹窗状态变化
const handlePopupChange = (e) => {
    if (!e.show) {
        // 关闭时清理
        isFocus.value = false;
        isSubmitting.value = false;
        inputBottom.value = 0;
        keyboardHeight.value = 0;
        isShow.value = false;
        clearTimeout(keepFocusTimer.value);
        wasOpenedBeforeHide.value = false;
        androidFocusLock.value = false;
        androidBlurCount.value = 0;
        params.content = '';
        params.images = [];
    } else {
        // 打开时确保聚焦
        setTimeout(() => {
            if (isAndroid.value) {
                safeForceFocus();
            } else {
                forceFocus();
            }
        }, 100);
    }
};

// 打开弹窗
const open = () => {
    if (popupRef.value) {
        isSubmitting.value = false;
        androidFocusLock.value = false;
        androidBlurCount.value = 0;
        popupRef.value.open();

        setTimeout(() => {
            isShow.value = true;
            // 延迟聚焦确保弹窗完全渲染
            setTimeout(() => {
                if (isAndroid.value) {
                    safeForceFocus();
                } else {
                    forceFocus();
                }
            }, 150);
        }, 100);
    }
};

// 输入框聚焦
const inputFocus = (e) => {
    console.log('输入框获得焦点 - 平台:', isAndroid.value ? 'Android' : 'iOS');
    if (keyboardHeight.value === 0 && pageVisible.value) {
        const systemInfo = uni.getSystemInfoSync();
        paddingHeight.value = isAndroid.value ? 30 : systemInfo.safeAreaInsets.bottom || 10;
        inputBottom.value = (isAndroid.value ? 30 : e.detail.height || 50) - paddingHeight.value;
    }
    
    // 安卓：聚焦时重置计数
    if (isAndroid.value) {
        androidBlurCount.value = 0;
    }
};

// 输入框失去焦点 - 安卓和iOS分别处理
const inputBlur = (e) => {
    console.log('输入框失去焦点 - 平台:', isAndroid.value ? 'Android' : 'iOS');

    clearTimeout(keepFocusTimer.value);

    if (isAndroid.value) {
        // 安卓特殊处理
        androidBlurCount.value++;
        console.log('安卓失去焦点计数:', androidBlurCount.value);
        
        // 只在特定条件下重新聚焦
        if (isShow.value && !isSubmitting.value && pageVisible.value && 
            keyboardHeight.value > 0 && androidBlurCount.value <= 3) {
            
            keepFocusTimer.value = setTimeout(() => {
                if (isShow.value && !isSubmitting.value && pageVisible.value && 
                    keyboardHeight.value > 0 && !androidFocusLock.value) {
                    console.log('安卓执行重新聚焦');
                    safeForceFocus();
                }
            }, 200);
        }
    } else {
        // iOS处理
        if (isShow.value && !isSubmitting.value && pageVisible.value && keyboardHeight.value > 0) {
            keepFocusTimer.value = setTimeout(() => {
                if (isShow.value && !isSubmitting.value && pageVisible.value && keyboardHeight.value > 0) {
                    console.log('iOS执行重新聚焦');
                    forceFocus();
                }
            }, 150);
        }
    }
};

const removeIMG = (index) => {
    params.images.splice(index, 1);
};

const chooseFENGMIAN = async (e) => {
    clearTimeout(keepFocusTimer.value);
    // 短暂失去焦点以避免与选择图片冲突
    isFocus.value = false;
    if (isAndroid.value) {
        androidFocusLock.value = true;
    }
    
    try {
        const remainingCount = 9 - params.images.length;
        if (remainingCount <= 0) {
            toast('最多只能上传9张图片');
            return;
        }
        
        const newImages = await chooseAndUploadImage({
            count: remainingCount,
            uploadText: '上传中...',
            sourceType: ['album']
        });
        params.images = [...params.images, ...newImages];
    } catch (err) {
        console.error('图片上传失败：', err);
        toast('图片上传失败');
    } finally {
        // 上传完成后重新聚焦
        if (isShow.value && pageVisible.value) {
            setTimeout(() => {
                if (isAndroid.value) {
                    androidFocusLock.value = false;
                    safeForceFocus();
                } else {
                    forceFocus();
                }
            }, 300);
        }
    }
};

const props = defineProps({
    id: {
        type: Number,
        required: true
    }
});

const params = reactive({
    id: undefined,
    content: '',
    images: []
});

const emit = defineEmits(['resetList']);

// 提交评论
const submitComment = () => {
    if (!btnactive.value) {
        toast('请输入评论内容');
        return;
    }
    
    params.id = props.id;
    isSubmitting.value = true;
    
    const submitData = {
        id: params.id,
        content: params.content,
        images: params.images.length > 0 ? params.images.join(',') : ''
    };
    
    articleReply(submitData).then((res) => {
        if (res.code == 200) {
            toast('已发表评论');
            emit('resetList');
            closePop();
        }
    }).catch(err => {
        console.error('评论提交失败:', err);
        toast('评论提交失败');
        isSubmitting.value = false;
    });
};

const confirmInput = (e) => {
    submitComment();
};

defineExpose({ open, closePop });

onUnmounted(() => {
    clearTimeout(keepFocusTimer.value);
    uni.$off('pageShow');
    uni.$off('pageHide');
});
</script>
<style lang="scss" scoped>
.input_pop {
	position: fixed;
	width: 100%;
	background: #ffffff;
	padding: 30rpx 20rpx;
	box-sizing: border-box;
	/* 添加过渡动画使移动更平滑 */
	transition: bottom 0.3s ease;
	/* 确保在键盘上方 */
	z-index: 99999;
	/* 添加阴影提升视觉效果 */
	box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
}
.input {
	width: 100%;
	background: #f7f7f7;
	border-radius: 20rpx;
	padding: 16rpx 20rpx;
	box-sizing: border-box;
	transition: border-color 0.2s ease;
}
.input-inner {
	width: 100%;
	min-height: 60rpx; /* 最小高度 */
	max-height: 200rpx; /* 限制最大高度避免过高 */
	background: transparent;
	font-size: 28rpx;
	color: #333;
	border: none;
	resize: none;
	outline: none;
	/* 改善文本显示 */
	line-height: 1.5;
	/* 确保滚动流畅 */
	overflow-y: auto;
}
.imglist {
	display: flex;
	flex-wrap: wrap;
	margin-top: 15rpx;
	.items {
		width: 80rpx;
		height: 80rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
		position: relative;
		image {
			display: block;
			width: 80rpx;
			height: 80rpx;
			border-radius: 6rpx 6rpx 6rpx 6rpx;
		}
		.icon {
			width: 24rpx;
			height: 24rpx;
			top: -8rpx;
			right: -8rpx;
			position: absolute;
			z-index: 1;
		}
	}
	.items1 {
		width: 80rpx;
		height: 80rpx;
		border-radius: 6rpx;
		background: #ffffff;
	}
}
.button_f {
	margin: 14rpx auto;
	image {
		width: 48rpx;
		height: 48rpx;
	}
	.btn {
		width: 152rpx;
		height: 60rpx;
		background: #ffffff;
		border-radius: 80rpx 80rpx 80rpx 80rpx;
		border: 1px solid #d1d1d6;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #d1d1d6;
		text-align: center;
		line-height: 60rpx;
	}
	.btn_active {
		background: #e3d0ad;
		color: #75613e;
		border: 1px solid #e3d0ad;
	}
}

/* 针对不同平台的微调 */
@media (platform: android) {
	.input_pop {
		padding-bottom: 20rpx; /* Android可能需要更多底部内边距 */
	}
}
@media (platform: ios) {
	.input_pop {
		padding-bottom: 10rpx; /* iOS可以少一些 */
	}
}
</style>
